package com.itwxz.games.controller;

import com.itwxz.common.core.domain.R;
import com.itwxz.common.exception.ServiceException;
import com.itwxz.games.domain.werewolf.WCreateRoomInfo;
import com.itwxz.games.domain.werewolf.WIdentity;
import com.itwxz.games.domain.werewolf.WRoom;
import com.itwxz.games.service.WerewolfService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/games/werewolf")
public class WerewolfController {

    private final WerewolfService werewolfService;

    @PostMapping("/create-room")
    public R<WRoom> createRoom(@RequestBody WCreateRoomInfo info) {
        WRoom r = werewolfService.createRoom(info);
        return R.ok(r);
    }

    /**
     * 加入房间
     * 前端传 roomId
     * 返回分配到的身份
     */
    @GetMapping("/join-room")
    public R<WIdentity> joinRoom(@RequestParam String roomId) {
        try {
            WIdentity identity = werewolfService.joinRoom(roomId);
            if (identity.getId() == 0) {
                // 加锁失败或房间已满
                return R.fail("加入房间失败，请重试");
            }
            return R.ok(identity);
        } catch (ServiceException e) {
            // 自定义异常处理
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("加入房间异常", e);
            return R.fail("系统异常，请稍后重试");
        }
    }

    @GetMapping("/check-room")
    public R<Boolean> checkRoom(@RequestParam String roomId) {
        return werewolfService.checkRoom(roomId);
    }

    @GetMapping("/close-room")
    public R<Boolean> closeRoom(@RequestParam String roomId) {
        return werewolfService.closeRoom(roomId);
    }
}
